import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'dart:io';

Effect<RefuseIndoorState> buildEffect() {
  return combineEffects(<Object, Effect<RefuseIndoorState>>{
    RefuseIndoorAction.onTapAddPic: _onTapAddPic,
    RefuseIndoorAction.onTapPic: _onTapPic,
    RefuseIndoorAction.onSetIndex: _onSetIndex,
    RefuseIndoorAction.onSubmit: _onSubmit,
  });
}

void _onSetIndex(Action action, Context<RefuseIndoorState> ctx) {
  if (ctx.state.selectIndex == action.payload) return;
  ctx.state.selectIndex = action.payload;
  CommonUtils.closeKey(ctx.context);
  ctx.dispatch(RefuseIndoorActionCreator.onAction());
}

void _onTapAddPic(Action action, Context<RefuseIndoorState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 0, info: ctx.state.model);
  if (imgFile != null) {
    ctx.dispatch(RefuseIndoorActionCreator.setOrderPhoto(imgFile));
  }
}

void _onTapPic(Action action, Context<RefuseIndoorState> ctx) async {
  pushPhoto(file) async {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: ctx.state.orderPhoto.indexOf(file),
      files: ctx.state.orderPhoto,
    );
  }

  var file = action.payload;
  int res =
  await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
  if (res == 1) {
    ctx.state.orderPhoto.remove(file);
    ctx.dispatch(RefuseIndoorActionCreator.onAction());
  } else if (res == 0) {
    pushPhoto(file);
  }
}

void _onSubmit(Action action, Context<RefuseIndoorState> ctx) async {
  if (ctx.state.selectIndex == 1 &&
      ctx.state.textEditingController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请填写问题描述');
    return;
  }
  String img = '';
  if (ctx.state.orderPhoto.length != 0) {
    CommonUtils.showWaitLoading(ctx.context, descText: '上传图片中');
    List<String> images =
    await CommonNetWork.multiUploadImgs(ctx.state.orderPhoto);
    Navigator.pop(ctx.context);
    img = images.join(',');
  }
  String reason;
  if (ctx.state.selectIndex == 0)
    reason =
    ctx.state.selectReason == 0 ? '安检人员多次上门，家中无人。' : '用户电话接通，另约上门安检时间。';
  else
    reason = ctx.state.textEditingController.text;
  CommonUtils.showWaitLoading(ctx.context);
  ResultData res = await CommonNetWork.setIndoorStatus(
    ctx.state.model.orderID,
    reason: reason,
    communityID: ctx.state.model.communityID,
    status: ctx.state.selectIndex == 0 ? '2' : '3',
    userID: ctx.state.model.userID,
    imgs: img,
  );
  Navigator.pop(ctx.context);
  if (res.success) {
    bus.emit('refreshList');
    await CommonUtils.showAlertView(ctx.context, '提交成功');
    Navigator.pop(ctx.context);
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}
